home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3879 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  59 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: Philip Staite <pstaite@vnet.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Pointers HELP!!!!
  5. Date: Fri, 26 Jan 1996 08:36:37 -0600
  6. Organization: IBM Rochester, OS/2 Device Driver Team
  7. Message-ID: <3108E6F5.167E@vnet.ibm.com>
  8. References: <31055e1d.1020193@news.pi.se> <DLpK20.6Co@prl.research.philips.com>
  9. NNTP-Posting-Host: powertool.rchland.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b4 (X11; I; AIX 1)
  14.  
  15. Richard B Sagar wrote:
  16. > You can only pass a pointer to a function if the function is a static
  17. > member function ... @.@ ... or is it a member function of a static class.
  18.  
  19. Maybe in the case he/she was using...  But in general, you can pass a
  20. pointer to any member.  Ptrs to non static member functions just aren't
  21. very useful unless you have an instance to bind them to.  But, if you've
  22. got an instance and a ptr to a mfn...  Try the following example:
  23.  
  24. #include<iostream.h>
  25. #include<stdlib.h>
  26. #include<time.h>
  27.  
  28. class foo {
  29.   public:
  30.     foo() : fp( foo::bar ) {}
  31.     void next() { fp = ( rand() & 4 ) ? foo::bar : foo::baz; }
  32.     void run() { (this->*fp)(); }
  33.     void bar() { cout << "foo::bar()" << endl; }
  34.     void baz() { cout << "foo:baz()" << endl; }
  35.   private:
  36.     void (foo::*fp)();
  37. };
  38.  
  39.  
  40. void finish( foo* f, void (foo::*fp)() ) {
  41.     cout << "Finished, calling last function..." << endl;
  42.     (f->*fp)(); }
  43.  
  44.  
  45. int main() {
  46.     srand( time( 0 ) );
  47.     foo f;
  48.     for( int i = 0 ; i++ < 10 ; f.next() )
  49.         f.run();
  50.     finish( &f, foo::bar );
  51.     return 0; }
  52.  
  53.  
  54. -- 
  55.  
  56. Phil Staite, (507) 253-2529, team OS/2
  57. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  58.